package com.imagefake.config.handler;

import com.alibaba.fastjson2.JSON;
import com.imagefake.util.JwtRedisUtil;
import com.imagefake.util.JwtUtils;
import com.imagefake.vo.HttpResult;
import com.imagefake.vo.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private JwtRedisUtil jwtRedisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 认证成功后的处理逻辑
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        //获取认证用户对象
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        //获取用户信息并传话为JSON
        String userInfo = JSON.toJSONString(securityUser.getSysUser());
        //获取用户权限并转换为JSON
        List<SimpleGrantedAuthority> tempList = (List<SimpleGrantedAuthority>) securityUser.getAuthorities();
        List<String> authorityList = tempList.stream()
                .map(SimpleGrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        //创建JWT
        String jwtToken = jwtUtils.createToken(userInfo, authorityList);
        //向Redis中存入用户JWT以及权限信息
        if (!jwtRedisUtil.isJwtExists(jwtToken)) {
            //如果在redis中未存入JWT再存入JWT
            jwtRedisUtil.insertJwt(jwtToken, JSON.toJSONString(authorityList));
        }
        //返回jwt
        HttpResult httpResult = new HttpResult(200, "登陆成功", jwtToken);
        String httpResultJSON = JSON.toJSONString(httpResult);
        response.getWriter().print(httpResultJSON);
        response.getWriter().flush();
    }
}
